package com.study.hot.jetpack.demo_words.ui

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.study.hot.R
import com.study.hot.jetpack.demo_words.db.Words
import com.study.hot.jetpack.demo_words.viewmodel.WordsViewModel
import kotlinx.android.synthetic.main.fragment_add_words.*
import org.jetbrains.anko.sdk27.coroutines.onClick

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/04/05
 *     desc   :
 * </pre>
 */
class AddWordsFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_add_words, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val wordsViewModel = ViewModelProvider(requireActivity())[WordsViewModel::class.java]
        submitBtn.isEnabled = false
        //弹出软键盘
        englistEt.requestFocus()
        val inputService = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputService.showSoftInput(englistEt, 0)
        chineseEt.addTextChangedListener(textWatcher)
        englistEt.addTextChangedListener(textWatcher)
        submitBtn.onClick { v ->
            val english = englistEt.text.toString().trim()
            val chinese = chineseEt.text.toString().trim()
            val words = Words(chinese, english)
            wordsViewModel.insertWords(words)
            //返回
            val findNavController = Navigation.findNavController(v!!)
            findNavController.navigateUp()
        }
    }

    val textWatcher = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            submitBtn.isEnabled = chineseEt.text.toString().trim().isNotEmpty()
                    && englistEt.text.toString().trim().isNotEmpty()
        }
    }
}